package com.lkj.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class SignUtil {

    public static boolean checkSignature(String token,String signature,String timestamp,String nonce){

        String[] arr = new String[]{token,timestamp,nonce};
        Arrays.sort(arr);

        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }

        MessageDigest md = null;
        String temStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes());
            temStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return temStr != null ? temStr.equals(signature.toUpperCase()):false;
    }

    /**
     * 将字节数组转换为16进制字符串
     * @param digest
     * @return
     */
    private static String byteToStr(byte[] digest){
        StringBuilder strDigest = new StringBuilder();
        for (int i = 0; i < digest.length; i++) {
            strDigest.append(byteToHexStr(digest[i]));
        }

        return strDigest.toString();
    }

    /**
     * 将字节转换为16进制字符串
     * @param b
     * @return
     */
    private static String byteToHexStr(byte b){
        char[] Digit = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F',};
        char[] temArr = new char[2];
        temArr[0] = Digit[(b>>>4 & 0X0F)];
        temArr[1] = Digit[b & 0X0F];

        return new String(temArr);
    }
}
